package info.webest.media.activities;

import info.webest.media.Options;
import info.webest.media.R;
import info.webest.pref.PrefFragment;

import java.util.List;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceManager;

public class PrefActivity extends PreferenceActivity implements
		OnSharedPreferenceChangeListener {

	private static Activity activity;
	private boolean needResource = false;
	private static boolean RefreshUI = false;

	@Override
	public void onBackPressed() {
		// super.onBackPressed();

		Intent intent = new Intent();
		intent.putExtra("RefreshUI", RefreshUI);
		setResult(RESULT_OK, intent);
		finish();
	}

	@Override
	protected boolean isValidFragment(String fragmentName) {
		// if(StockPreferenceFragment.class.getName().equals(fragmentName))
		// return true;
		// return false;
		return true;
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public void onBuildHeaders(List<Header> target) {
		if (onIsHidingHeaders() || !onIsMultiPane()) {
			needResource = true;
		} else {
			loadHeadersFromResource(R.xml.preference_headers, target);
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		// Theme
		setTheme(Options.getThemeId());

		super.onCreate(savedInstanceState);

		activity = this;

		if (needResource
				|| Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
			// addPreferencesFromResource(R.xml.preferences);
			onCreatePreferenceActivity();
		}
	}

	@SuppressWarnings("deprecation")
	private void onCreatePreferenceActivity() {
		// Load the XML preferences file
		// addPreferencesFromResource(R.xml.preferences);
		addPreferencesFromResource(R.xml.preference_common);
		addPreferencesFromResource(R.xml.preference_user_interface);
		addPreferencesFromResource(R.xml.preference_files_folders);

		for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
			initSummary(getPreferenceScreen().getPreference(i));
		}
	}

	public static class CommonFragment extends PrefFragment {
		@Override
		public void onCreate(Bundle savedInstanceState) {
			// Load the preferences from an XML resource
			xml_id = R.xml.preference_common;

			super.onCreate(savedInstanceState);

			// Make sure default values are applied. In a real app, you would
			// want this in a shared function that is used to retrieve the
			// SharedPreferences wherever they are needed.

			// PreferenceManager.setDefaultValues(getActivity(),
			// R.xml.advanced_preferences, false);

			// Can retrieve arguments from preference XML.
			// Log.i("args", "Arguments: " + getArguments());
		}

		@Override
		public void onSharedPreferenceChanged(
				SharedPreferences sharedPreferences, String key) {

			PrefActivity.Check(sharedPreferences, key);
			super.onSharedPreferenceChanged(sharedPreferences, key);
		}
	}

	/**
	 * This fragment shows the preferences for the second header.
	 */
	public static class UIFragment extends PrefFragment {
		@Override
		public void onCreate(Bundle savedInstanceState) {
			xml_id = R.xml.preference_user_interface;
			super.onCreate(savedInstanceState);
		}

		@Override
		public void onSharedPreferenceChanged(
				SharedPreferences sharedPreferences, String key) {

			PrefActivity.Check(sharedPreferences, key);
			super.onSharedPreferenceChanged(sharedPreferences, key);
		}
	}

	/**
	 * This fragment shows the preferences for the second header.
	 */
	public static class FilesFragment extends PrefFragment {
		@Override
		public void onCreate(Bundle savedInstanceState) {
			xml_id = R.xml.preference_files_folders;
			super.onCreate(savedInstanceState);
		}

		@Override
		public void onSharedPreferenceChanged(
				SharedPreferences sharedPreferences, String key) {

			PrefActivity.Check(sharedPreferences, key);
			super.onSharedPreferenceChanged(sharedPreferences, key);
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onResume() {
		super.onResume();
		// Set up a listener whenever a key changes
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {

			getPreferenceScreen().getSharedPreferences()
					.registerOnSharedPreferenceChangeListener(this);
		} else {
			PreferenceManager.getDefaultSharedPreferences(this)
					.registerOnSharedPreferenceChangeListener(this);
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onPause() {
		super.onPause();
		// Unregister the listener whenever a key changes
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
			getPreferenceScreen().getSharedPreferences()
					.unregisterOnSharedPreferenceChangeListener(this);
		} else {
			PreferenceManager.getDefaultSharedPreferences(this)
					.unregisterOnSharedPreferenceChangeListener(this);
		}
	}

	public static void Check(SharedPreferences sharedPreferences, String key) {
		String s = null;

		if (key.equals(Options.SHOW_WHEN_LOCKED)) {
			Options.ShowWhenLocked = sharedPreferences.getBoolean(key,
					Options.ShowWhenLocked);
		}

		if (key.equals(Options.KEEP_NOTIFICATION)) {
			Options.KeepNotification = sharedPreferences.getBoolean(key,
					Options.KeepNotification);
		}

		if (key.equals(Options.HEADSET_PLUG)) {
			Options.HeadsetPlug = sharedPreferences.getBoolean(key,
					Options.HeadsetPlug);
		}

		if (key.equals(Options.HEADSET_UNPLUG)) {
			Options.HeadsetUnplug = sharedPreferences.getBoolean(key,
					Options.HeadsetUnplug);
		}

		if (key.equals(Options.HEADSET_BUTTON)) {
			Options.HeadsetButton = sharedPreferences.getBoolean(key,
					Options.HeadsetButton);
		}

		if (key.equals(Options.VOLUME_INDICATOR)) {
			Options.VolumeIndicator = sharedPreferences.getBoolean(key,
					Options.VolumeIndicator);
		}

		if (key.equals("ScreenTheme")) {
			s = sharedPreferences.getString(key, "Dark");
			if (s.equals("Dark")) {
				Options.Theme = Options.ScreenTheme.THEME_DARK;

			} else if (s.equals("Light")) {
				Options.Theme = Options.ScreenTheme.THEME_LIGHT;

			}

			// Theme
			activity.getApplication().setTheme(Options.getThemeId());
			activity.finish();
			activity.startActivity(new Intent(activity, activity.getClass()));
		}

		if (key.equals("ScreenOrientation")) {
			s = sharedPreferences.getString(key, "Auto");
			if (s.equals("Portrait")) {
				Options.Orientation = Options.ScreenOrientation.SCREEN_PORTRAIT;

			} else if (s.equals("Landscape")) {
				Options.Orientation = Options.ScreenOrientation.SCREEN_LANDSCAPE;

			} else if (s.equals("Auto")) {
				Options.Orientation = Options.ScreenOrientation.SCREEN_AUTO;
			}
		}

		if (key.equals(Options.VOLUME_CONTROL)) {
			Options.VolumeControl = sharedPreferences.getBoolean(key,
					Options.VolumeControl);
		}

		if (key.equals(Options.EQUALIZER)) {
			Options.Equalizer = sharedPreferences.getBoolean(key,
					Options.Equalizer);
		}

		if (key.equals(Options.FAST_SCROLL)) {
			Options.FastScroll = sharedPreferences.getBoolean(key,
					Options.FastScroll);
		}

		if (key.equals(Options.FONT_SIZE)) {
			s = sharedPreferences.getString(key, "" + Options.FontSize);
			Options.FontSize = Integer.valueOf(s);
			RefreshUI = true;

		}
		if (key.equals(Options.LINE_SPACING)) {
			s = sharedPreferences.getString(key, "" + Options.LineSpacing);
			Options.LineSpacing = Integer.valueOf(s);
			RefreshUI = true;
		}

		// Files and Folders

		if (key.equals(Options.SHOW_FOLDER_SIZE)) {
			Options.ShowFolderSize = sharedPreferences.getBoolean(key,
					Options.ShowFolderSize);
		}

		if (key.equals(Options.COUNT_FOLDER_ELEMENTS)) {
			Options.CountFolderElements = sharedPreferences.getBoolean(key,
					Options.CountFolderElements);
		}

		if (key.equals(Options.SHOW_FILE_EXT)) {
			Options.ShowFileExt = sharedPreferences.getBoolean(key,
					Options.ShowFileExt);
		}

		if (key.equals(Options.SHOW_FILE_SIZE)) {
			Options.ShowFileSize = sharedPreferences.getBoolean(key,
					Options.ShowFileSize);
		}

		if (key.equals(Options.SHOW_DURATION)) {
			Options.ShowDuration = sharedPreferences.getBoolean(key,
					Options.ShowDuration);
		}
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {

		Check(sharedPreferences, key);
		updatePrefSummary(key);
	}

	private void initSummary(Preference p) {
		if (p instanceof PreferenceCategory) {
			PreferenceCategory pCat = (PreferenceCategory) p;
			for (int i = 0; i < pCat.getPreferenceCount(); i++) {
				initSummary(pCat.getPreference(i));
			}
		} else {
			updatePrefSummary(p);
		}
	}

	@SuppressWarnings("deprecation")
	private void updatePrefSummary(String key) {

		Preference p = findPreference(key);
		updatePrefSummary(p);
	}

	private void updatePrefSummary(Preference p) {

		if (p instanceof ListPreference) {
			ListPreference listPref = (ListPreference) p;
			p.setSummary(listPref.getEntry());
		}
	}

}
